package cn.schoolwow.util.module.check.jsonarray.flow.check;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.jsonarray.QueryJSONArray;
import com.alibaba.fastjson.JSONArray;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class CheckJSONArrayNotRepeatFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        List<String> fieldNames = (List<String>) flowContext.getData("fieldNames");
        JSONArray array = (JSONArray) flowContext.checkData("array");
        String message = (String) flowContext.checkData("message");

        if(null==fieldNames||fieldNames.isEmpty()){
            throw new IllegalArgumentException(message+"的字段名称列表不能为空");
        }

        List repeatList = new ArrayList<>();
        for(int i=0;i<array.size();i++){
            String[] fieldNameArray = fieldNames.toArray(new String[0]);
            Object fieldValue = QueryJSONArray.newQuery(array)
                    .execute()
                    .getMultipleFieldValueList(fieldNameArray);
            if(fieldValue instanceof Collection){
                repeatList.clear();
                Collection collection = (Collection) fieldValue;
                for(Object singleCollectionValue:collection){
                    if(repeatList.contains(singleCollectionValue)){
                        throw new IllegalArgumentException(message+"包含重复值!重复值:["+singleCollectionValue+"]");
                    }
                    repeatList.add(singleCollectionValue);
                }
            }
        }

    }

    @Override
    public String name() {
        return "实例列表-检查列表值是否有重复值";
    }
}
